/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.bemanager.dependency;

import com.inspur.edp.bef.bemanager.util.BefFileUtil;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.Element;

public class ModifyPomUtil {

  private ModifyPomUtil() {

  }

  public static ModifyPomUtil getInstance() {
    return new ModifyPomUtil();
  }

  /**
   * 修改{projectPath}pom文件
   *
   * @param projectPath
   * @param dependencyArrayList
   */
  public void modifyPom(String projectPath, ArrayList<MavenDependency> dependencyArrayList) {
    if (dependencyArrayList == null || dependencyArrayList.size() == 0) {
      return;
    }
    String pomPath = BefFileUtil.getPomFilePath(projectPath);
    Document doc = readDocument(pomPath);
    Element projectElement = doc.getRootElement();
    Element dependenciesElement = projectElement.element(MavenDependencyConst.dependencies);

    if (dependenciesElement == null) {
      dependenciesElement = projectElement.addElement(MavenDependencyConst.dependencies);
    }
    List<Element> existValues = dependenciesElement.elements();
    ArrayList<MavenDependency> existDependencies = readExistDependencies(existValues);
    for (MavenDependency newDependency : dependencyArrayList) {
      if (checkContainDependency(newDependency, existDependencies)) {
        continue;
      }
      addDependencyDom(newDependency, dependenciesElement);
    }
    saveDocument(doc, new File(pomPath));
  }

  /**
   * 读取默认的依赖配置
   *
   * @return
   */
  public ArrayList<MavenDependency> getDefaultDependency() {
    String defaultDependencyPath =
        this.getClass().getResource("/BefProjectMavenDependency.xml").toString();
    return readInternalDependency(defaultDependencyPath);
  }

  /**
   * 读取扩展的依赖配置
   *
   * @return
   */
  public ArrayList<MavenDependency> getExtendDependency() {
    String extendDependencyPath =
        this.getClass().getResource("/BefExtendMavenDependency.xml").toString();
    return readInternalDependency(extendDependencyPath);
  }

  /**
   * 读取Sgf扩展的依赖配置
   *
   * @return
   */
  public ArrayList<MavenDependency> getSgfExtendDependency() {
    String extendDependencyPath =
        this.getClass().getResource("/SgfExtendMavenDependency.xml").toString();
    return readInternalDependency(extendDependencyPath);
  }

  private ArrayList<MavenDependency> readInternalDependency(String defaultDependencyPath) {
    ArrayList<MavenDependency> result = new ArrayList<>();
    Document doc = readDocument(defaultDependencyPath);
    Element rootElement = doc.getRootElement();
    List<Element> list = rootElement.elements();
    for (int i = 0; i < list.size(); i++) {
      Element ele = list.get(i);
      result.add(new MavenDependency(getTagValue(ele, MavenDependencyConst.groupId),
          getTagValue(ele, MavenDependencyConst.artifactId),
          getTagValue(ele, MavenDependencyConst.version),
          getTagValue(ele, MavenDependencyConst.file)));
    }
    return result;
  }

  // region 私有方法
  private ArrayList<MavenDependency> readExistDependencies(List<Element> existValues) {
    ArrayList<MavenDependency> list = new ArrayList<>();
    if (existValues == null || existValues.size() == 0) {
      return list;
    }
    for (int i = 0; i < existValues.size(); i++) {
      Element ele = existValues.get(i);
      list.add(new MavenDependency(getTagValue(ele, MavenDependencyConst.groupId),
          getTagValue(ele, MavenDependencyConst.artifactId),
          getTagValue(ele, MavenDependencyConst.version)));
    }
    return list;
  }

  private boolean checkContainDependency(MavenDependency dependency,
      ArrayList<MavenDependency> dependencies) {
    for (MavenDependency item : dependencies) {
      if (item.equals(dependency)) {
        return true;
      }
    }
    return false;
  }

  private void addDependencyDom(MavenDependency dependency, Element parentElement) {
    Element element = parentElement.addElement(MavenDependencyConst.dependency);
    Element gourpId = element.addElement(MavenDependencyConst.groupId);
    Element artifactId = element.addElement(MavenDependencyConst.artifactId);
    gourpId.setText(dependency.getGroupId());
    artifactId.setText(dependency.getArtifactId());
    if (dependency.getVersion() != null && !dependency.getVersion().isEmpty()) {
      Element version = element.addElement(MavenDependencyConst.version);
      version.setText(dependency.getVersion());
    }
  }

  private String getTagValue(Element ele, String tagName) {
    return BefFileUtil.getTagValue(ele, tagName);
  }

  private Document readDocument(String filePath) {
    return BefFileUtil.readDocument(filePath);
  }

  private void saveDocument(Document document, File xmlFile) {
    BefFileUtil.saveDocument(document, xmlFile);
  }
  // endregion
}
